package com.ews.onlineexchange.controller;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;

import javax.annotation.ManagedBean;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import com.ews.onlineexchange.model.Attachment;
import com.ews.onlineexchange.util.AttachmentUtils;
import com.ews.onlineexchange.util.Config;

@ManagedBean
@Named
public class FileDownloadView {
	
		private StreamedContent file;
		
	    public StreamedContent getFile() {
	        return file;
	    }
	    @Inject
	    Config config;
		public StreamedContent download(Attachment attachment) throws UnsupportedEncodingException{
			HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
			String contentType = req.getSession().getServletContext().getMimeType(attachment.getFilename());
			String saveDir = config.getProperty("com.ews.onlineExchange.saveDir");
	        String fullPath = saveDir + attachment.getFilepath();
			file = new DefaultStreamedContent(new ByteArrayInputStream(AttachmentUtils.getBytes(fullPath)),contentType,attachment.getFilename());
			return file;
	    }   
	    
}
